﻿using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace AutoF3
{
    public static class ConvertTexToHtml
    {
        public static string ConvertToHtml(string tex)
        {
            string regex = "(\\$\\$.*?\\$\\$)|(\\$.*?\\$)|(\\$\\$[^\\$]*?$)|(\\$[^\\$]*?$)"; //do we want to do this when there's only an opening $?
            RegexOptions options = (RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline);

            Regex reg = new Regex(regex, options);
            var htmlStr = reg.Replace(tex, new MatchEvaluator(ReplaceWithImageTag));

            return AdditionalCleanup(htmlStr);
        }

        private static string ReplaceWithImageTag(Match m)
        {
            string str = m.ToString();
            string tex = str.Replace("$", "");
            int length = str.Length;

            if (length < 2 || str[1] != '$') //single $ mode
                return GetTexImageTag(tex);
            else
                return "<br /><br />" + GetTexImageTag(tex) + "<br /><br />";
        }

        private static string GetTexImageTag(string tex)
        {
            return "<img src=\"http://latex.codecogs.com/gif.latex?" + tex + "\" alt=\"" + tex + "\" style=\"vertical-align: -3px\">";
        }

        private static string AdditionalCleanup(string tex)
        {
            int index = tex.IndexOf("\\emph{");
            string ret = tex;

            while (index >= 0) 
            {
                int openBracketIndex = index + "\\emph{".Length - 1;
                int closeBracketIndex = GetMatchingBracketIndex(tex, openBracketIndex);

                if (closeBracketIndex >= 0)
                {
                    string toReplace = tex.Substring(index, (closeBracketIndex - index) + 1);
                    string stringWithinBrackets = tex.Substring(openBracketIndex + 1, toReplace.Length - "\\emph{}".Length);

                    ret = ret.Replace(toReplace, "<span style=\"font-style:italic\">" + stringWithinBrackets + "</span>");
                }

                index = tex.IndexOf("\\emph{", index + 1);
            }

            return ret;
        }

        private static int GetMatchingBracketIndex(string str, int index)
        {
            int currDepth = 1;

            for (int i = index + 1; i < str.Length; i++)
            {
                if (str[i] == '{')
                    currDepth++;
                else if (str[i] == '}')
                    currDepth--;

                if (currDepth == 0)
                    return i;
            }

            return -1;
        }
    }
}
